import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# from proving.models import *
from django.conf import settings
from django.contrib.auth.models import User
import socket
import json
import requests

fromMail = "ST"
# HOST = settings.ALLOWED_HOSTS[0]
# HOST = "10.149.6.159"
# toMail = ["nsdi-sdp-dbs@mail.foxconn.com"]  # , "james.xj.zhang@mail.foxconn.com"] # 这里可以添加多个收件人
# cc = ["nsdi-sdp-web@mail.foxconn.com"]
# bcc = ["nsdi-sdp-media@mail.foxconn.com"]

# smtpHost = "10.134.34.241"        # 自己的邮件服务器
# smtpPort = "587"

smtpHost = "10.134.28.95"       # 主
# smtpHost = "10.134.99.142"      # 备
smtpPort = "25"

myname = socket.getfqdn(socket.gethostname())
myaddr = socket.gethostbyname(myname)

def sendMail(toMail, sub, content, cc="", html="False"):      # 发送邮件函数
    """
    :param toMail:  收件人，可以为多个，以逗号分隔
    :param sub:     邮件标题
    :param content: 邮件内容
    :param cc:      抄送人，格式与收件人相同
    :param html:    是否需要发送HTML格式，默认为"False", 需注意此处为字符串类型
    :return:        status , result
    """
    # msg = MIMEMultipart()
    # msg['From'] = fromMail
    # msg['Subject'] = sub
    # msg['To'] = type(toMail) != list and toMail or ",".join(toMail)     # 不是List类型就直接赋值，List类型下需要进行转换
    toMail = type(toMail) != list and toMail or ",".join(toMail)     # 不是List类型就直接赋值，List类型下需要进行转换(调用Postbay用)
    # acManager = User.objects.filter(is_superuser=True)[0]
    # content = content+"\n\n\n ACManager:"+acManager.first_name+" \n AC地址：" + HOST + "\n ACManagerMail:" + acManager.email+"\nExt:"+acManager.userprofile.ext    # +"\n FromName--->"+myname+"\n FromIP--->"+myaddr
    # if cc:
    #     msg['Cc'] = cc

    # cont = MIMEText(content, _subtype='plain', _charset='utf-8')
    # msg.attach(cont)

    # logs = MIMEText(file.read() , 'base64', 'gb2312')
    # logs["Content-Type"] = 'application/octet-stream'
    # logs["Content-Disposition"] = 'attachment; filename="error.txt"'
    # msg.attach(logs)

    # 发送多个附件使用
    # py = MIMEText(open('c:/Users/F1330319/Desktop/MyPy/mail.py', 'rb').read(), 'base64', 'utf-8')
    # py["Content-Type"] = 'application/octet-stream'
    # py["Content-Disposition"] = 'attachment; filename="mail.py"'
    # msg.attach(py)
    # sub = "[通知郵件]"+sub
    try:
        content = content + "\n\t系統地址：" + settings.EMAIL_TEMPLATE["HOST"] + "\n\n" \
                  "\t如有疑問請聯繫管理員：" + settings.EMAIL_TEMPLATE["Manager"] + "\n" \
                  "\t此郵件來源於《基準烽火雲台》，由系統自動發送，請勿回复！\n\n"

        data = {"system_name": "基準烽火雲台", "toMail": toMail, "content": content, "mail_title": sub, "cc": cc,
                "html_status": html, "errors_type": "通知郵件"}
        url = 'http://10.129.4.95:9090/data_manage/'
        r = requests.post(url, data=json.dumps(data))
        r.json()
        return True, r
        # smtp = smtplib.SMTP(smtpHost,smtpPort)
        # smtp.set_debuglevel(1)
        # smtp.docmd("HELO Server")
        # smtp.ehlo("ismetoad")
        # smtp.starttls()
        # smtp.helo("ismetoad")
        # if cc:
        #     smtp.sendmail(fromMail, [toMail, cc], msg.as_string())
        # else:
        #     smtp.sendmail(fromMail, [toMail], msg.as_string())
        # smtp.close()
        # return True
    except Exception as error:
        # content = str(error)
        # writeLog("function/send_mail/->"+content)
        return False


def SMTPMail(toMail, sub, content, cc=None):      # 发送邮件函数
    """
    :param toMail:  收件人，可以为多个，以逗号分隔
    :param sub:     邮件标题
    :param content: 邮件内容
    :param cc:      抄送人，格式与收件人相同
    :param html:    是否需要发送HTML格式，默认为"False", 需注意此处为字符串类型
    :return:        status , result
    """
    msg = MIMEMultipart()
    msg['From'] = fromMail
    msg['Subject'] = sub
    msg['To'] = type(toMail) != list and toMail or ",".join(toMail)     # 不是List类型就直接赋值，List类型下需要进行转换
    # acManager = User.objects.filter(is_superuser=True)[0]
    # content = content+"\n\n\n ACManager:"+acManager.first_name+" \n AC地址：" + HOST + "\n ACManagerMail:" + acManager.email+"\nExt:"+acManager.userprofile.ext    # +"\n FromName--->"+myname+"\n FromIP--->"+myaddr

    if cc:
        msg['Cc'] = cc

    cont = MIMEText(content, _subtype='plain', _charset='utf-8')
    msg.attach(cont)

    # 发送附件
    # logs = MIMEText(file.read() , 'base64', 'gb2312')
    # logs["Content-Type"] = 'application/octet-stream'
    # logs["Content-Disposition"] = 'attachment; filename="error.txt"'
    # msg.attach(logs)

    # 发送多个附件使用
    # py = MIMEText(open('c:/Users/F1330319/Desktop/MyPy/mail.py', 'rb').read(), 'base64', 'utf-8')
    # py["Content-Type"] = 'application/octet-stream'
    # py["Content-Disposition"] = 'attachment; filename="mail.py"'
    # msg.attach(py)
    try:
        smtp = smtplib.SMTP(smtpHost,smtpPort)
        smtp.set_debuglevel(1)
        smtp.docmd("HELO Server")
        smtp.ehlo("ismetoad")
        smtp.starttls()
        smtp.helo("ismetoad")
        if cc:
            smtp.sendmail(fromMail, [toMail, cc], msg.as_string())
        else:
            smtp.sendmail(fromMail, [toMail], msg.as_string())
        smtp.close()
        return True
    except Exception as error:
        # content = str(error)
        # writeLog("function/send_mail/->"+content)
        return False


def jobNumberSendMail(num, sub, content, ccNum=None):
    toMail = User.objects.filter(username__iexact=num)[0]
    content = "您好，"+toMail.first_name+":\n"+content
    if ccNum:
        ccMail = User.objects.filter(username__iexact=ccNum)[0]
        sendMail(toMail.email, sub, content, cc=ccMail.email)
        return True
    sendMail(toMail.email, sub, content)
    return True
